package main

import (
	// "flag"

	"fmt"
	"io"
	"log"
	"os"
	"time"
	"yuqueDownloader/util"
	"yuqueDownloader/yuqueRequest"
)

var cookieStr string

func init() {

	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	f, _ := os.OpenFile(".\\Cookies.txt", os.O_RDONLY, 0644)
	b, _ := io.ReadAll(f)
	cookieStr = string(b)

}

func main() {

	cookiesMap := util.WithdrawCookie(cookieStr)
	session := cookiesMap["_yuque_session"]
	ctoken := cookiesMap["yuque_ctoken"]
	log.Printf("session: %s, ctoken: %s\n", session, ctoken)

	request := yuqueRequest.InitParam("https://www.yuque.com",
		session,
		ctoken)

	appData, appDataStr := request.GetAppData("/jiangnanyidianyujavaboyorg/kzmgpd/oq4ggkz891zkiocb")

	log.Println("appData ========>", appData)

	startTime := time.Now()
	if appData != nil {
		bookName := appData.Book.Name
		bookId := appData.Book.Id

		dirPath := fmt.Sprintf(".%cresult%c%s", os.PathSeparator, os.PathSeparator, bookName)
		err := os.RemoveAll(dirPath)
		if err != nil {
			log.Fatalf("RemoveAll %s ERROR:%v\n", dirPath, err)
		}

		request.BaseDirPath = dirPath

		go util.WriteFile(appDataStr,
			"appData",
			dirPath,
			fmt.Sprintf("%d-appdata-golang.json", bookId),
			&request.Wg)

		for idx, toc := range appData.Book.Tocs {
			toc.Idx = idx
			go request.HandleToc(appData.Book, toc)
		}

	}
	request.Wg.Wait()

	endTime := time.Now()

	log.Printf("%s 下载工作已完成, 耗时: %s\n", appData.Book.Name, (endTime.Sub(startTime)))

}
